﻿<template>
  <div class="app-container">
    <div class="chart-title">档案管理</div>
    <div class="chart-content">
      <div class="filter-title">
        <el-form label-position="right" @submit.native.prevent>
          <el-form-item>
            <el-input
              v-model="listQuery.goods_name"
              style="width: 160px; height:32px;"
              class="filter-item"
              :placeholder="$t('goods.name_1')"
              @keyup.enter.native="handleFilter"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-date-picker
              style="width: 160px; height:32px;"
              v-model="listQuery.goods_date"
              align="right"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="排餐日期"
            >
            </el-date-picker>
          </el-form-item>
          <div class="search-button" @click="handleFilter">
            <img src="@/assets/images/bg_search@2x.png" />
          </div>
          <div class="search-button" @click="handleRefresh">
            <img src="@/assets/images/bg_reset@2x.png" />
          </div>
        </el-form>
        <div class="filter-right">
          <div class="add-button" @click="handleCreate">
            <img src="@/assets/images/icon_add@2x.png" />
            <span>新建</span>
          </div>
        </div>
      </div>
      <div class="chart-list">
        <el-table
          :key="tableKey"
          v-loading="listLoading"
          :data="list"
          element-loading-text="拼命加载中"
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(255,255,255,0.2)"
          border
          fit
          highlight-current-row
          style="width: 100%min-height:1000px"
        >
          <el-table-column
            fixed="left"
            align="center"
            :label="$t('table.id')"
            width="65"
          >
            <template slot-scope="scope">
              <span>{{
                (listQuery.page - 1) * listQuery.limit + scope.$index + 1
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            show-overflow-tooltip
            :label="$t('public.date')"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.goods_date }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            show-overflow-tooltip
            :label="$t('meal.name')"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.goods_name }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            show-overflow-tooltip
            :label="$t('public.pictrue')"
          >
            <template slot-scope="scope">
              <el-image
                style="width: 100px; height: 100px"
                :src="scope.row.goods_main_img"
                fit="contain"
              ></el-image>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            show-overflow-tooltip
            :label="$t('public.creationTime')"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.create_time }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            show-overflow-tooltip
            :label="$t('operator.name')"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.nickname }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            show-overflow-tooltip
            :label="$t('operator.name')"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.nickname }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            show-overflow-tooltip
            :label="$t('public.status')"
          >
            <template slot-scope="scope">
              <span>{{ mealsStatus(scope.row.status) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            show-overflow-tooltip
            :label="$t('operator.name')"
          >
            <template slot-scope="scope">
              <div
                class="release-button"
                v-if="scope.row.status === 4"
                @click="releaseData(scope.row.goods_date)"
              >
                {{ $t("table.release") }}
              </div>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            :label="$t('table.actions')"
            fixed="right"
          >
            <template slot-scope="scope">
              <div class="operat-button">
                <div class="read-img" @click="handleRead(scope.row.goods_date)">
                  <img src="@/assets/images/read@2x.png" />
                </div>
                <div
                  v-if="scope.row.status === 1"
                  class="read-img"
                  @click="handleModifyStatus(scope.row, 'deleted')"
                >
                  <img src="@/assets/images/delete@2x.png" />
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination-container">
        <el-pagination
          background
          :current-page="listQuery.page"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="listQuery.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
      <!-- 排餐 -->
      <el-dialog
        :title="textMap[dialogStatus]"
        :visible.sync="dialogFormVisible"
      >
        <div class="pops-item-special">
          <div class="date-item">
            <div class="date-title">日期：</div>
            <div class="date-content">
              <el-date-picker
                v-model="temp.goods_date"
                align="right"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                :picker-options="pickerOptions"
              ></el-date-picker>
            </div>
          </div>
          <div class="table-special">
            <div class="custom-heand">
              <div class="custom-items">序号</div>
              <div class="custom-items">供应商</div>
              <div class="custom-items">餐品</div>
              <div class="custom-items">预订价</div>
              <div class="custom-items">限购价</div>
            </div>
            <div
              v-for="(items, index) in temp.list"
              :key="index"
              class="custom-body"
            >
              <div class="custom-items">{{ index + 1 }}</div>
              <div class="custom-items">{{ items.supplier_name }}</div>
              <div class="custom-items">
                <drop-down-select
                  :data="goodsOptions"
                  :count="goodsCount"
                  :page-size="pageSize"
                  :id="items.goods_id"
                  :name="items.goods_name"
                  @getList="
                    (pageNumber, search) => {
                      return getGoods(pageNumber, search, 'getGoods');
                    }
                  "
                  @addList="
                    (pageNumber, search) => {
                      return getGoods(pageNumber, search, 'addGoods');
                    }
                  "
                  @choose="
                    data => {
                      return choose(data, index, 'goods');
                    }
                  "
                  @remove="
                    data => {
                      return remove(data, index, 'goods');
                    }
                  "
                ></drop-down-select>
              </div>
              <div class="custom-items">
                <el-input-number
                  v-model="items.front_price"
                  :min="0"
                ></el-input-number>
              </div>
              <div class="custom-items">
                <el-input-number
                  v-model="items.buy_price"
                  :min="0"
                ></el-input-number>
              </div>
            </div>
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">{{
            $t("table.cancel")
          }}</el-button>
          <el-button
            type="primary"
            :disabled="!createDisabled"
            @click="createData(1)"
            >{{ $t("table.save") }}</el-button
          >
          <el-button
            type="primary"
            :disabled="!createDisabled"
            @click="createData(2)"
            >{{ $t("table.send_2") }}</el-button
          >
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script type="text/javascript">
import dropDownSelect from "@/views/select/dropDownSelect"; // 分页选择控件
import { getToken } from "@/utils/auth";
export default {
  name: "Itoc",
  components: {
    "drop-down-select": dropDownSelect
  },
  data() {
    const validateName = (rule, value, callback) => {
      // return false
      if (value.length > 0) {
        if (value.length > 20) {
          callback(new Error("名称长度不能大于20个字符"));
        } else {
          var reg = /^(?!(\d+)$)(?!(\_+)$)[\u4e00-\u9fff\w]+$/; /* 定义验证表达式 */
          if (reg.test(value)) {
            /* 进行验证 */
            callback();
          } else {
            callback(
              new Error("名称只能包含汉字、英文、“_”和数字且不为纯数字或纯符号")
            );
          }
        }
      } else {
        callback(new Error("请填写名称"));
      }
    };
    return {
      tableKey: 0,
      list: null,
      total: null,
      listLoading: true,
      deadlineOptions: [
        {
          value: 1,
          label: "1年"
        },
        {
          value: 2,
          label: "2年"
        },
        {
          value: 3,
          label: "3年"
        },
        {
          value: 99,
          label: "不限"
        }
      ],
      listQuery: {
        page: 1,
        limit: 20,
        name: "",
        code: "",
        status: "",
        linkname: "",
        linkname_mobile: "",
        region_name: "",
        region_type: ""
      },
      avaiableDateList: [],
      pickerOptions: {
        disabledDate: time => {
          var date = this.timestampToTime(time, "{y}-{m}-{d}");
          return (
            this.avaiableDateList.includes(date) ||
            time.getTime() < new Date().getTime()
          );
        }
      },
      districtsOptions: [],
      LastDateTimestamp: undefined,
      temp: {
        goods_date: "",
        type: 1,
        list: []
      },
      dialogFormVisible: false,
      dialogVisible: false,
      dialogStatus: "",
      textMap: {
        edit: "编辑",
        create: "新建排餐",
        review: "审核",
        read: "查看"
      },
      editrules: {
        name: [{ required: true, trigger: "blur", validator: validateName }]
      },
      createDisabled: true,
      saveDisabled: false,
      updateDisabled: true,
      goodsOptions: [],
      goodsCount: undefined,
      pageSize: 20
    };
  },
  created() {
    const token = getToken();
    if (
      token &&
      !this.$store.state.socket.loginTransition &&
      !this.$store.state.socket.loginAccount
    ) {
      this.tokenLogin(token);
    }
    this.getList();
  },
  methods: {
    tokenLogin(token) {
      const path = {
        app: "wxadmin",
        api: "api_wxadmin_admin_keepLogin",
        version: "1.0",
        type: 2,
        data: {
          token: token
        }
      };
      this.socketApi.sendSock(JSON.stringify(path), res => {
        this.socketData(res);
      });
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList();
    },
    handleRefresh() {
      this.listQuery = {
        page: 1,
        limit: 20,
        goods_name: "",
        goods_date: ""
      };
      this.getList();
    },
    // 获取排餐列表
    getList() {
      this.listLoading = true;
      const data = {
        rows: this.listQuery.limit,
        page: this.listQuery.page,
        goods_name: this.listQuery.goods_name ? this.listQuery.goods_name : "",
        goods_date: this.listQuery.goods_date ? this.listQuery.goods_date : ""
      };
      const path = {
        app: "user",
        api: "api_arrange_index_getList",
        version: "1.0",
        type: 2,
        data: data
      };
      this.socketApi.sendSock(JSON.stringify(path), res => {
        if (res) {
          this.socketData(res);
        }
      });
    },
    // 获取已排餐日期
    getArrangedList() {
      const path = {
        app: "arrange",
        api: "api_arrange_index_getTime",
        version: "1.0",
        type: "1",
        data: {}
      };
      this.socketApi.sendSock(JSON.stringify(path), res => {
        if (res) {
          this.socketData(res);
        }
      });
    },
    // 获取供应商列表
    getSupplier() {
      const path = {
        app: "arrange",
        api: "api_arrange_index_supplieList",
        version: "1.0",
        type: 2,
        data: {}
      };
      this.socketApi.sendSock(JSON.stringify(path), res => {
        if (res) {
          this.socketData(res);
        }
      });
    },
    handleCreate() {
      // this.resetTemp();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.getSupplier();
      this.getArrangedList();
      // 打开查看弹窗
    },
    // 打开查看弹窗
    handleRead(goods_date) {
      this.$router.push({
        path: "/meal-manage/meals-list-detail",
        query: {
          goods_date: goods_date.split(" ")[0]
        }
      });
      // this.temp = Object.assign({}, row); // copy obj
      // this.dialogStatus = "read";
      // this.dialogFormVisible = true;
      // this.$nextTick(() => {
      //   this.$refs["dataForm"].clearValidate();
      // });
    },
    // 编辑排餐
    handleEdit(row) {
      this.temp = Object.assign({}, row); // copy obj
      this.dialogStatus = "edit";
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs["editForm"].clearValidate();
      });
    },
    // 添加排餐
    createData(type) {
      console.log("this.temp.list", this.temp.list);
      const path = {
        app: "arrange",
        api: "api_arrange_index_add",
        version: "1.0",
        type: 2,
        data: {
          goods_date: this.temp.goods_date ? this.temp.goods_date : "",
          type: type,
          list: this.temp.list ? this.temp.list : ""
        }
      };
      console.log("JSON.stringify(path)", JSON.stringify(path));
      this.socketApi.sendSock(JSON.stringify(path), res => {
        if (res) {
          this.socketData(res);
        }
        setTimeout(() => {
          this.createDisabled = true;
        }, 1000);
      });
    },
    // 更新排餐
    updateData() {
      this.$refs["editForm"].validate(valid => {
        if (valid) {
          if (this.updateDisabled) {
            this.updateDisabled = false;
            const data = {
              id: this.temp.id,
              goods_id: this.temp.goods_id
            };
            const path = {
              app: "arrange",
              api: "api_arrange_index_edit",
              version: "1.0",
              type: "1,2",
              data: data
            };
            this.socketApi.sendSock(JSON.stringify(path), res => {
              if (res) {
                this.socketData(res);
              }
              setTimeout(() => {
                this.updateDisabled = true;
              }, 1000);
            });
          }
        }
      });
    },
    releaseData(date) {
      const path = {
        app: "arrange",
        api: "api_arrange_index_openProducts",
        version: "1.0",
        type: 2,
        data: {
          goods_date: date
        }
      };
      this.socketApi.sendSock(JSON.stringify(path), res => {
        if (res) {
          this.socketData(res);
        }
      });
    },
    handleModifyStatus(row) {
      this.$confirm("此操作将永久删除该职员信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          const path = {
            app: "arrange",
            api: "api_arrange_index_delete",
            version: "1.0",
            type: 2,
            data: {
              goods_date: row.goods_date
            }
          };
          console.log("JSON.stringify(path)", JSON.stringify(path));
          this.socketApi.sendSock(JSON.stringify(path), res => {
            if (res) {
              this.socketData(res);
            } else {
              this.$message.error(" 删除失败 ");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 商品选择
    getGoods(pageNumber, search, name) {
      const path = {
        app: "goods",
        api: "api_goods_index_getList",
        version: "1.0",
        type: 2,
        data: {
          rows: this.pageSize,
          page: pageNumber || 1,
          name: search || "",
          returnType: name || ""
        }
      };
      this.socketApi.sendSock(JSON.stringify(path), res => {
        if (res) {
          this.socketData(res);
        }
      });
    },
    choose(data, index, name) {
      if (name === "goods") {
        this.temp.list[index].goods_id = data.id;
        this.temp.list[index].goods_name = data.name;
      }
    },
    remove(index, name) {
      if (name === "goods") {
        this.temp.list[index].goods_id = undefined;
        this.temp.list[index].goods_name = "";
      }
    },
    socketData(res) {
      if (res !== '{"type":"ping"}') {
        const resj = JSON.parse(res);
        if (resj.code === -1) {
          this.$message.error(resj.message);
        } else {
          if (resj.api === "api_wxadmin_admin_keepLogin") {
            this.$store.dispatch("loginTransition", true);
            this.socketApi.sendCache(res => {
              this.socketData(res);
            });
          } else if (resj.api === "api_arrange_index_getList") {
            this.total = resj.count;
            this.list = resj.data;
            console.log("this.list", this.list);
            this.listLoading = false;
          } else if (resj.api === "api_arrange_index_getTime") {
            console.log("resj.", resj.data);
            this.avaiableDateList = resj.data;
          } else if (resj.api === "api_arrange_index_supplieList") {
            console.log("resj.", resj.data);
            const supplierList = [];
            resj.data.forEach(element => {
              supplierList.push({
                supplier_id: element.supplier_id,
                supplier_name: element.supplier_name,
                goods_id: "",
                goods_name: "",
                buy_price: 0,
                front_price: 0
              });
            });
            this.temp.list = supplierList;
            console.log("this.temp.list", this.temp.list);
          } else if (resj.api === "api_archives_itoc_sevenRegional") {
            this.districtsOptions = resj.data;
          } else if (
            resj.api === "api_goods_index_getList" &&
            resj.type === "getGoods"
          ) {
            this.goodsOptions = resj.data;
            console.log("this.goodsOptions", this.goodsOptions);
            this.goodsCount = resj.count;
          } else if (
            resj.api === "api_goods_index_getList" &&
            resj.type === "addGoods"
          ) {
            this.goodsOptions = this.goodsOptions.concat(resj.data);
          } else if (resj.api === "api_arrange_index_add") {
            this.$notify({
              title: "成功",
              message: "添加成功",
              type: "success",
              duration: 2000
            });
            this.dialogFormVisible = false;
            this.getList();
          } else if (resj.api === "api_arrange_index_edit") {
            this.$notify({
              title: "成功",
              message: "更新成功",
              type: "success",
              duration: 2000
            });
            this.dialogVisible = false;
            this.getList();
          } else if (resj.api === "api_arrange_index_delete") {
            this.$notify({
              title: "成功",
              message: "删除成功",
              type: "success",
              duration: 2000
            });
            this.getList();
          } else if (resj.api === "api_arrange_index_openProducts") {
            this.$notify({
              title: "成功",
              message: "发布成功",
              type: "success",
              duration: 2000
            });
            this.getList();
          }
        }
      }
    },
    // 比较时间
    dataCompare(date) {
      // 排餐日期
      const time = new Date(date).getTime();
      // 当前日期
      const now = this.timestampToTime(new Date().getTime(), "{y}-{m}-{d}");
      // 加四个小时变成12:00
      const nowTimestamp = new Date(now).getTime() + 4 * 60 * 60 * 1000;
      if (time < nowTimestamp + 3 * (24 * 60 * 60 * 1000)) {
        return true;
      } else {
        return false;
      }
    }
  }
};
</script>
<style scoped>
.pops-left-sp {
  widows: 30%;
}
.pops-right-sp {
  widows: 30%;
}
.release-button {
  width: 72px;
  height: 32px;
  background: rgba(228, 234, 248, 1);
  border-radius: 16px;
  margin: auto;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  color: rgba(102, 102, 102, 1);
  line-height: 1;
}
.pops-item-special {
  padding: 20px;
}
.date-item,
.custom-heand,
.custom-body {
  display: flex;
  align-items: center;
}
.table-special {
  margin-top: 20px;
}
.custom-heand {
  height: 40px;
  background: rgba(240, 242, 245, 1);
  border-radius: 4px 4px 0px 0px;
  font-size: 14px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  color: rgba(139, 148, 190, 1);
  line-height: 1;
}
.custom-body {
  height: 40px;
  border-bottom: 1px solid #e0e0e0;
}
.custom-heand .custom-items:not(:first-child),
.custom-body .custom-items:not(:first-child) {
  flex: 1;
}
.custom-heand .custom-items:first-child,
.custom-body .custom-items:first-child {
  width: 65px;
  padding-left: 10px;
  box-sizing: border-box;
}
</style>
